﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using EMPower.Enum;
using System.Drawing.Imaging;
using System.IO;

namespace BLL.Common
{
    public class ImageHandle
    {
        #region 字段

        public const decimal BigBasicWidth = 600;//大图宽
        public const decimal BigBacisHeight = 250;//大图高
        public const decimal SmallBasicWidth = 140;//小图宽
        public const decimal SmallBacisHeight = 100;
        private int ImageHeight;
        private int ImageWidth;
        private Image ResourceImage;
        private string sourceimgPath;//图片源路径
        public string ErrMessage;//错误信息
        private bool _islegal = false;
        private int _basicWidth = 0;//图片宽
        private int _basicHeight = 0;//图片高

        #endregion

        #region 属性

        /// <summary>
        /// 合法
        /// </summary>
        public bool IsLegal
        {
            get
            {
                return _islegal;
            }
        }

        /// <summary>
        /// 宽
        /// </summary>
        public int Width
        {
            get
            {
                return _basicWidth;
            }
        }

        /// <summary>
        /// 高
        /// </summary>
        public int Height
        {
            get
            {
                return _basicHeight;
            }
        }

        /// <summary>
        /// 图片的宽最小值
        /// </summary>
        public int MinimumWidth
        {
            get
            {
                return Convert.ToInt32(BigBasicWidth);
            }
        }

        /// <summary>
        /// 图片的高最小值
        /// </summary>
        public int MinimumHeight
        {
            get
            {
                return Convert.ToInt32(BigBacisHeight);
            }
        }

        #endregion

        #region 初始化

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ImageFileName">图片路径</param>
        public ImageHandle(string ImageFileName)
        {
            Init(ImageFileName);
        }
        /// <summary>
        /// 构造函数（2012-9-21 多语言）
        /// </summary>
        /// <param name="ImageFileName">图片路径</param>
        /// <param name="codeType"></param>
        public ImageHandle(string ImageFileName, LanguageCode codeType)
        {
            Init(ImageFileName, codeType);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="ImageFileName">图片路径</param>
        private void Init(string ImageFileName)
        {
            this.ErrMessage = "";
            this.sourceimgPath = ImageFileName;

            if (!string.IsNullOrEmpty(ImageFileName))
            {
                bool isok = false;
                try
                {
                    this.ResourceImage = Image.FromFile(ImageFileName);
                    if (ResourceImage != null)
                    {
                        _basicWidth = this.ResourceImage.Width;
                        _basicHeight = this.ResourceImage.Height;
                        if (Width >= SmallBasicWidth && Height >= SmallBacisHeight)
                        {
                            isok = true;
                        }
                        else
                        {
                            ErrMessage = "对不起，您要上传的图片:宽不小于" + SmallBasicWidth.ToString() + " 高不小于" + SmallBacisHeight.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrMessage = e.Message;
                }
                finally
                {
                    if (isok)
                    {
                        _islegal = true;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化（2012-9-21 多语言）
        /// </summary>
        /// <param name="ImageFileName">图片路径</param>
        /// <param name="codeType"></param>
        private void Init(string ImageFileName, LanguageCode codeType)
        {
            this.ErrMessage = "";
            this.sourceimgPath = ImageFileName;

            if (!string.IsNullOrEmpty(ImageFileName))
            {
                bool isok = false;
                try
                {
                    this.ResourceImage = Image.FromFile(ImageFileName);
                    if (ResourceImage != null)
                    {
                        _basicWidth = this.ResourceImage.Width;
                        _basicHeight = this.ResourceImage.Height;
                        if (Width >= SmallBasicWidth && Height >= SmallBacisHeight)
                        {
                            isok = true;
                        }
                        else
                        {
                            //ErrMessage = "对不起，您要上传的图片:宽不小于" + SmallBasicWidth.ToString() + " 高不小于" + SmallBacisHeight.ToString();
                            ErrMessage = string.Format(LanguageHelper.GetLabel("Common.ImgHandle", codeType), SmallBasicWidth.ToString(), SmallBacisHeight.ToString());
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrMessage = e.Message;
                }
                finally
                {
                    if (isok)
                    {
                        _islegal = true;
                    }
                }
            }
        }

        /// <summary>
        /// 销毁对象
        /// </summary>
        public void DestroyImg()
        {
            if (ResourceImage != null)
            {
                ResourceImage.Dispose();
            }
        }

        /// <summary>
        /// 将图片写到流里
        /// </summary>
        /// <param name="imageToConvert"></param>
        /// <param name="formatOfImage"></param>
        /// <returns></returns>
        private static byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
        {
            byte[] Ret;

            try
            {

                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    Ret = ms.ToArray();
                }
            }
            catch (Exception) { throw; }

            return Ret;
        }


        #endregion

        #region CoCreation压缩

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="path">保存路径</param>
        public void NoChangeSave(string path)
        {
            if (this.ResourceImage != null)
            {
                this.ResourceImage.Save(path);
                DestroyImg();
            }
        }

        /// <summary>
        /// 压缩页面图片
        /// </summary>
        /// <param name="width">要压缩的宽</param>
        /// <param name="height">要压缩的高</param>
        /// <param name="savePath">压缩完保存的路径</param>
        /// <param name="isCompel">是否强制缩放，如果图片在合法范围之内是不是要按照目标宽高压缩。 true:强制 false:否</param>
        /// <returns></returns>
        public bool GetCutImg(int width, int height, string savePath, bool isCompel)
        {
            bool isok = false;

            if (isCompel)
            {
                //强制压缩  
                if ((decimal)width / this.Width < (decimal)height / this.Height)
                {
                    //宽
                    MakeThumbnail(this.sourceimgPath, savePath, width, height, "W");
                    isok = true;
                }
                else if (height == 0)
                {
                    //宽
                    MakeThumbnail(this.sourceimgPath, savePath, width, height, "W");
                    isok = true;
                }
                else if (width == 0)
                {
                    MakeThumbnail(this.sourceimgPath, savePath, width, height, "H");
                    isok = true;
                }
                else
                {
                    //高         
                    MakeThumbnail(this.sourceimgPath, savePath, width, height, "H");
                    isok = true;
                }
            }
            else
            {
                if (width > this.Width && height > this.Height || width > this.Width && height == 0)
                {
                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }
                    File.Copy(this.sourceimgPath, savePath);
                }
                else
                {
                    //需要压缩  
                    if ((decimal)width / this.Width < (decimal)height / this.Height)
                    {
                        //宽
                        MakeThumbnail(this.sourceimgPath, savePath, width, height, "W");
                        isok = true;
                    }
                    else if (height == 0)
                    {
                        //宽
                        MakeThumbnail(this.sourceimgPath, savePath, width, height, "W");
                        isok = true;
                    }
                    else if (width == 0)
                    {
                        MakeThumbnail(this.sourceimgPath, savePath, width, height, "H");
                        isok = true;
                    }
                    else
                    {
                        //高         
                        MakeThumbnail(this.sourceimgPath, savePath, width, height, "H");
                        isok = true;
                    }
                }
            }
            DestroyImg();

            return isok;
        }

        /// <summary>
        /// 压缩详情图
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public bool GetBigImg(string savePath)
        {
            bool isok = false;

            if (IsLegal)
            {
                MakeThumbnail(this.sourceimgPath, savePath, 480, 0, "W");

                isok = true;

            }
            return isok;
        }

        /// <summary>
        /// 压缩列表图
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public bool GetSmallImg(string savePath)
        {
            bool isok = false;

            if (IsLegal)
            {
                if (GetCutImg((int)SmallBasicWidth, (int)SmallBacisHeight, savePath, false))
                {
                    isok = true;
                }
            }
            return isok;
        }

        #endregion

        #region 基本压缩方法

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="Percent">压缩比率 50% --> 0.5</param>
        /// <returns></returns>
        public Image GetReducedImage(double Percent)
        {
            try
            {
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
                this.ImageWidth = Convert.ToInt32((double)(this.ResourceImage.Width * Percent));
                this.ImageHeight = Convert.ToInt32((double)(this.ResourceImage.Width * Percent));
                return this.ResourceImage.GetThumbnailImage(this.ImageWidth, this.ImageHeight, callback, IntPtr.Zero);
            }
            catch (Exception exception)
            {
                this.ErrMessage = exception.Message;
                return null;
            }
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="Percent">压缩比率 50% --> 0.5 </param>
        /// <param name="targetFilePath">另存路径</param>
        /// <returns>成功与否</returns>
        public bool GetReducedImage(double Percent, string targetFilePath)
        {
            try
            {
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
                this.ImageWidth = Convert.ToInt32((double)(this.ResourceImage.Width * Percent));
                this.ImageHeight = Convert.ToInt32((double)(this.ResourceImage.Width * Percent));
                Image image = this.ResourceImage.GetThumbnailImage(this.ImageWidth, this.ImageHeight, callback, IntPtr.Zero);
                image.Save(targetFilePath, ImageFormat.Jpeg);
                image.Dispose();
                return true;
            }
            catch (Exception exception)
            {
                this.ErrMessage = exception.Message;
                return false;
            }
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <returns></returns>
        public Image GetReducedImage(int Width, int Height)
        {
            try
            {
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
                return this.ResourceImage.GetThumbnailImage(Width, Height, callback, IntPtr.Zero);
            }
            catch (Exception exception)
            {
                this.ErrMessage = exception.Message;
                return null;
            }
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <param name="targetFilePath">另存路径</param>
        /// <returns></returns>
        public bool GetReducedImage(int Width, int Height, string targetFilePath)
        {
            try
            {
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
                Image image = this.ResourceImage.GetThumbnailImage(Width, Height, callback, IntPtr.Zero);
                // ＝＝＝处理JPG质量的函数＝＝＝
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                    {
                        ici = codec;
                        break;
                    }

                }
                EncoderParameters ep = new EncoderParameters();
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

                image.Save(targetFilePath, ici, ep);
                image.Dispose();
                return true;
            }
            catch (Exception exception)
            {
                this.ErrMessage = exception.Message;
                return false;
            }
        }

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="originalImagePath">原始图片路径</param>
        /// <param name="thumbnailPath">压缩完成图片的保存路径</param>
        /// <param name="width">压缩的宽</param>
        /// <param name="height">压缩的高</param>
        /// <param name="mode">压缩模式（W:宽  H:高  Cut:裁剪）</param>
        public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {

            DestroyImg();

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）
                    break;
                case "W"://指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            // ＝＝＝处理JPG质量的函数＝＝＝
            /*
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }

            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
            
            */
            try
            {
                //保存图片               
                //bitmap.Save(thumbnailPath,ImageFormat.Gif);   
                ImageFormat format = GetImageFormat(thumbnailPath.Substring(thumbnailPath.LastIndexOf(".") + 1));
                bitmap.Save(thumbnailPath, format);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        public void MakeThumbnail(string thumbnailPath, int width, int height, string mode)
        {

            System.Drawing.Image originalImage;
            byte[] myByteArray = ConvertImageToByteArray(this.ResourceImage, ImageFormat.Bmp);

            using (MemoryStream ms = new MemoryStream(myByteArray, 0, myByteArray.Length))
            {

                ms.Write(myByteArray, 0, myByteArray.Length);

                originalImage = Image.FromStream(ms, true);
            }


            DestroyImg();

            //System.Drawing.Image originalImage = System.Drawing.Image.FromStream(originalImageStream);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）
                    break;
                case "W"://指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

            // ＝＝＝处理JPG质量的函数＝＝＝
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }

            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

            try
            {
                //以jpg格式保存缩略图
                //bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                //ImageFormat format = GetImageFormat(thumbnailPath.Substring(thumbnailPath.LastIndexOf(".") + 1));
                bitmap.Save(thumbnailPath, ici, ep);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        public static bool MakeThumbnail(Stream str, string thumbnailPath, int width, int height, string mode)
        {

            System.Drawing.Image originalImage;
            bool falg = false;
            using (str)
            {
                originalImage = Image.FromStream(str, true);
            }

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）
                    break;
                case "W"://指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

            // ＝＝＝处理JPG质量的函数＝＝＝
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }

            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, ici, ep);
                falg = true;
            }
            catch (System.Exception e)
            {
                falg = false;
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

            return falg;
        }

        /// <summary>
        /// 给图片加水印
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="Path_sy"></param>
        protected void AddShuiYinWord(string Path, string Path_sy)
        {
            DestroyImg();
            string addText = "测试水印";
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            System.Drawing.Font f = new System.Drawing.Font("Verdana", 16);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);

            g.DrawString(addText, f, b, 15, 15);
            g.Dispose();

            image.Save(Path_sy);
            image.Dispose();
        }

        /// <summary>
        /// 在线给图片加水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
        /// <param name="Path_sypf">水印图片路径</param>
        protected void AddShuiYinPic(string Path, string Path_syp, string Path_sypf)
        {
            DestroyImg();
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(Path_syp);
            image.Dispose();
        }

        /// <summary>
        /// 缩小裁剪图片
        /// </summary>
        /// <param name="int_Width">要缩小裁剪图片宽度</param>
        /// <param name="int_Height">要缩小裁剪图片长度</param>
        /// <param name="input_ImgUrl">要处理图片路径</param>
        /// <param name="out_ImgUrl">处理完毕图片路径</param>
        public static bool ImgReduceCutOut(int startX, int startY, int int_Width, int int_Height, int cut_Width, int cut_Height, string input_ImgUrl, string out_ImgUrl)
        {
            bool flag = false;
            int CutOut_Width = int_Width; // 裁剪的宽度
            int CutOut_Height = int_Height; // 裁剪的高度
            int level = 100; //缩略图的质量 1-100的范围

            CutOut_Width = int_Width;
            CutOut_Height = int_Height;


            Bitmap bm = new Bitmap(input_ImgUrl);

            // ＝＝＝处理JPG质量的函数＝＝＝
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }

            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);


            try
            {

                // ＝＝＝裁剪图片＝＝＝
                Rectangle cloneRect = new Rectangle(startX, startY, CutOut_Width, CutOut_Height);
                PixelFormat format = bm.PixelFormat;
                Bitmap cloneBitmap = bm.Clone(cloneRect, format);
                bm.Dispose();
                // ===== 压缩图片 ======
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                cloneBitmap.Save(stream, ici, ep);
                // ＝＝＝保存图片＝＝＝
                MakeThumbnail(stream, out_ImgUrl, cut_Width, cut_Height, "HW");
                flag = true;
            }
            catch
            {

                bm.Save(out_ImgUrl);
                bm.Dispose();
                File.Delete(input_ImgUrl);
                flag = false;
            }


            return flag;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool ThumbnailCallback()
        {
            return false;
        }
        //获得图片格式　
        private static ImageFormat GetImageFormat(String extendName)
        {
            extendName = extendName.ToLower();
            if (extendName == "gif")
            {
                return ImageFormat.Gif;
            }
            else if (extendName == "jpg" || extendName == "jpeg")
            {
                return ImageFormat.Jpeg;
            }
            else if (extendName == "bmp")
            {
                return ImageFormat.Bmp;
            }
            else if (extendName == "wmf")
            {
                return ImageFormat.Emf;
            }
            else if (extendName == "exif")
            {
                return ImageFormat.Exif;
            }
            else if (extendName == "icon")
            {
                return ImageFormat.Icon;
            }
            else if (extendName == "tiff")
            {
                return ImageFormat.Tiff;
            }
            else
            {
                return ImageFormat.Png;
            }
        }
        #endregion
    }
}
